<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use service\LogService;
// use service\HxService;
use think\Db;
use think\db\Where;

/**
 * 前台用户管理控制器
 * Class Member
 * @package app\admin\controller
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/02/15 18:12
 */
class Member extends BasicAdmin
{

    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'Member';
    public $tableLog = 'MachineLog';
    public $tableReserve = 'Reserve';
    public $member;
    public $hx;
    public $area;
    public $mem_auto_id = 1;//用户表自增id

    public function _initialize()
    {
        parent::_initialize();
        $this->assign('roles', config('dbx.member_auth'));
    }
    /**
     * 用户列表
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function index()
    {
        $this->title = '用户管理';
        list($get, $db) = [$this->request->get(), Db::name($this->table)];
        foreach (['username', 'nickname', 'role', 'phone', 'mail', 'aid', 'nid', 'did'] as $key) {
            if(isset($get[$key]) && $get[$key] !== ''){
                if(in_array($key, ['aid', 'nid', 'did'])){
                    $db->where($key, 'eq', $get[$key]);
                    $db->whereOr($key, 'like', "{$get[$key]},%");
                    $db->whereOr($key, 'like', "%,{$get[$key]},%");
                    $db->whereOr($key, 'like', "%,{$get[$key]}");
                }elseif($key == 'role'){
                    $db->where($key, $get[$key]);
                }elseif($key == 'is_advisor'){
                    $db->where($key, $get[$key]);
                }else{
                    $db->whereLike($key, "%{$get[$key]}%");
                }
            }
        }
        if (isset($get['date']) && $get['date'] !== '') {
            list($start, $end) = explode(' - ', $get['date']);
            $db->whereBetween('login_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }
        return parent::_list($db->where(['is_deleted' => 0])->order('id desc'));
    }

    /**
     * 记录
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function trace()
    {
        $this->title = '记录';
        list($get, $db) = [$this->request->get(), Db::name($this->traceTable)];
        $db->order('trace_num desc');
        foreach (['keyword', 'aid', 'role'] as $key) {
            if(isset($get[$key]) && $get[$key] !== ''){
                if(($key == 'keyword') || ($key == 'role') || ($key == 'aid')){
                    $mMap = [];
                    $finalMap = $finalProMap = $finalMemMap = [
                        'status' => 1,
                        'is_deleted' => 0,
                    ];
                    // halt($get);
                    if($key == 'keyword'){
                        $finalProMap['title'] = ['like', "%{$get[$key]}%"];
                        // $finalProMap = new Where($finalProMap);

                        $finalMemMap['username|nickname'] = ['like', "%{$get[$key]}%"];
                        // $finalMemMap = new Where($finalMemMap);
                        $mems = $this->member->getColumn($finalMemMap,'id');
                        // halt($pros);
                        // halt($mems);
                        if($mems){
                            $mMap['id'] = ['in', $mems];
                        }
                    }
                    if($key == 'role'){
                        $mMap['role'] = $get[$key];
                    }
                    // $mids = $this->member->getColumn(['role' => $get[$key]], 'id');
                    // halt($mids);
                    // $db->where('create_by', 'in', $mids);
                // }elseif($key == 'aid'){
                    if($key == 'aid'){
                        $areas = $this->area->order('area_id asc')->select();
                        $aids = ToolsService::getArrSubIds($areas,$get[$key],'area_id','area_parent_id');//当前区域下地区Ids
                        if($aids){
                            $mMap['aid'] = ['in', $aids];
                        }
                    }
                    // $mMap = new Where($mMap);
                    $mids = $this->member->getColumn($mMap, 'id');
                    // halt($mids);
                    $db->where('uid', 'in', $mids);
                }else{
                    $db->whereLike($key, "%{$get[$key]}%");
                }
            }
        }
        if (isset($get['date']) && $get['date'] !== '') {
            list($start, $end) = explode(' - ', $get['date']);
            // $db->whereBetween('login_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
            $db->whereBetween('create_at', [strtotime("{$start} 00:00:00"), strtotime("{$end} 23:59:59")]);
        }
        return parent::_list($db->where(['is_deleted' => 0]));
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _trace_data_filter(&$data)
    {
        // halt($data);
        foreach ($data as &$vo) {
            $vo['aid'] = $this->member->getValue((['id' => $vo['uid']]), 'aid');
        }
        // halt($data);
    }

    /**
     * 授权管理
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function auth()
    {
        if ($this->request->isGet()) {
            // $this->assign('roles', config('pp.role_type'));
            return $this->_form($this->table, 'auth');
        }
        $post = $this->request->post();
        if(!isset($post['role'])){
            $this->error('请选择角色');                
        }
        $data = ['id' => $post['id'], 'role' => $post['role']];
        if (DataService::save($this->table, $data, 'id')) {
            LogService::write('系统用户', '系统用户授权成功');
            $this->success('修改成功');
        }
        $this->error('修改失败！');
    }

    /**
     * 用户添加
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function add()
    {
        // $rs = $this->hx->hx_register("pp".mt_rand(10000,99999), '111111', '123');
        // $ret  = json_decode($rs, true);
        // halt($ret);
        return $this->_form($this->table, 'form');
    }

    /**
     * 用户编辑
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function edit()
    {
        // $rs = $this->hx->hx_user_info($this->request->post('id'));
        // $ret  = json_decode($rs, true);
        // halt($ret);
        // if($ret['error'] == 'service_resource_not_found'){
        //     $this->error('找不到用户信息');
        // }
        return $this->_form($this->table, 'form');
    }

    /**
     * 用户密码修改
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function pass()
    {
        if ($this->request->isGet()) {
            $this->assign('verify', false);
            return $this->_form($this->table, 'pass');
        }
        $post = $this->request->post();
        if ($post['password'] !== $post['repassword']) {
            $this->error('两次输入的密码不一致！');
        }
        $username = get_model_value($post['id'], 'Member','username');
        $data = ['id' => $post['id'], 'password' => md5($post['password'])];
        if (DataService::save($this->table, $data, 'id')) {
            LogService::write('系统用户', '系统用户密码修改成功');
            // $rs = $this->hx->hx_user_update_password($username, $post['password']);
            // $ret  = json_decode($rs, true);
            // if(isset($ret['error'])){
            //     if($ret['error'] == 'duplicate_unique_property_exists'){
            //         $this->error("用户已存在");
            //     }else{
            //         $this->error($ret['error']);
            //     }
            // }
            $this->success('密码修改成功，下次请使用新密码登录！', '');
        }
        $this->error('密码修改失败，请稍候再试！');
    }

    /**
     * 表单数据默认处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _form_filter(&$data)
    {
        if ($this->request->isPost()) {
            // halt($data);
            if (isset($data['authorize']) && is_array($data['authorize'])) {
                $data['authorize'] = join(',', $data['authorize']);
            } else {
                $data['authorize'] = '';
            }
            
            // if(!isset($data['role'])){
            //     $this->error('请选择角色');                
            // }

            //用户名自定义 20191226 by pp
            // $data['username'] = 'asd'.$this->mem_auto_id;
            if (isset($data['id'])) {
                // halt($data);
                $data['update_at'] = time();
                $oldNickname = Db::name($this->table)->where('id', 'eq', $data['id'])->value('nickname');
                if(isset($data['nickname']) && $oldNickname != $data['nickname']){
                    // $rs = $this->hx->hx_user_update_nickname($data['username'], $data['nickname']);
                    // $ret  = json_decode($rs, true);
                    // if(isset($ret['error'])){
                    //     if($ret['error'] == 'duplicate_unique_property_exists'){
                    //         $this->error("用户已存在");
                    //     }else{
                    //         $this->error($ret['error']);
                    //     }
                    // }
                }

                if(isset($data['phone'])){
                    $editMap = ['phone' => $data['phone'], 'id' => ['neq', $data['id']]];
                    // $editMap = new Where($editMap);
                    if (Db::name($this->table)->where($editMap)->count() > 0) {
                        $this->error('手机号码已经存在，请使用其它手机号码！');
                    }                    
                }
                // unset($data['username']);
            } elseif (Db::name($this->table)->where(['username' => $data['username']])->count() > 0) {
                $this->error('账号已经存在，请使用其它账号！');
            } elseif (Db::name($this->table)->where(['truename' => $data['truename']])->count() > 0) {
                $this->error('姓名已经存在，请使用其它姓名！');
            } elseif (Db::name($this->table)->where(['phone' => $data['phone']])->count() > 0) {
                $this->error('手机号码已经存在，请使用其它手机号码！');
            }
            // if(!isset($data['aid']) || $data['aid'] == ''){
            //     $this->error('请选择地区');
            // }
            if(!isset($data['id'])){
                LogService::write('系统用户', '系统用户添加成功');
                //环信注册验证
                $data['password'] = '111111';//默认密码
                // $this->hxReg($data);
                $data['password'] = md5($data['password']);//默认密码
                $data['create_at'] = time();
            }else{
                LogService::write('系统用户', '系统用户修改成功');
            }
            // halt($data);
        } else {
            $data['authorize'] = explode(',', isset($data['authorize']) ? $data['authorize'] : '');
            // $this->assign('authorizes', Db::name('SystemAuth')->where(['status' => '1'])->select());
            // $this->assign('roles', config('pp.role_type'));
            
            if(!empty($data['readgroup'])){
                $data['readgroup']=explode(',',$data['readgroup']);
            }else{
                $data['readgroup'] = [1];
            }
            if(!empty($data['aid'])){
                $data['aid']=explode(',',$data['aid']);
            }
            if(!empty($data['nid'])){
                $data['nid']=explode(',',$data['nid']);
            }
            if(!empty($data['did'])){
                $data['did']=explode(',',$data['did']);
            }

            $newareas = ToolsService::arr2subs($this->newareas, $data['aid']);
            $this->assign('newareas', $newareas);
            $newnations = ToolsService::arr2subss($this->newnations, $data['nid']);
            $this->assign('newnations', $newnations);
            $newdiseases = ToolsService::arr2subss($this->newdiseases, $data['did']);
            $this->assign('newdiseases', $newdiseases);
        }
    }

    //批量审核
    public function statusAll(){
        $map['id'] =array('in',input('post.ids/a'));
        Db::name($this->table)->where($map)->update(['status'=>1]);
        LogService::write('会员', '会员批量审核成功');
        $result['code'] = 1;
        $result['msg'] = '批量审核成功！';
        $result['url'] = url('index',array('catid'=>input('post.catid')));
        return $result;
    }

    //取消批量审核
    public function statusCancelAll(){
        $map['id'] =array('in',input('post.ids/a'));
        Db::name($this->table)->where($map)->update(['status'=>0]);
        LogService::write('会员', '会员批量取消审核成功');
        $result['code'] = 1;
        $result['msg'] = '批量取消审核成功！';
        $result['url'] = url('index',array('catid'=>input('post.catid')));
        return $result;
    }

    // /**
    //  * 删除用户
    //  * @throws \think\Exception
    //  * @throws \think\exception\PDOException
    //  */
    // public function del()
    // {
    //     $ids = explode(',', $this->request->post('id'));
    //     // if (in_array('10000', explode(',', $this->request->post('id')))) {
    //     //     $this->error('系统超级账号禁止删除！');
    //     // }
        
    //     // halt($this->hx->hx_user_delete('pp0005'));
    //     // halt($this->member::get($this->request->post('id'))->delete());
    //     foreach($ids as $k => $v){
    //         $username = get_model_value($v, 'Member','username');
    //         // if (DataService::update($this->table)) {
    //         if ($this->member::get($v)->delete()) {
    //             LogService::write('系统用户', '系统用户删除成功');
    //             // $hx_delete = $this->hx->hx_user_delete($username);
    //             // if($hx_delete){
    //             //     $this->success("用户删除成功！", '');
    //             // }
    //         }
    //     }
    //     $this->success("用户删除成功！", '');
    //     // $this->error("用户删除失败，请稍候再试！");
    // }


    /**
     * 删除用户
     */
    public function del() {
        if (DataService::update($this->table)) {
            LogService::write('系统用户', '传承人用户删除成功');
            $this->success("用户删除成功！", '');
        }
        $this->error("用户删除失败，请稍候再试！");
    }
    /**
     * 用户禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        // if (in_array('10000', explode(',', $this->request->post('id')))) {
        //     $this->error('系统超级账号禁止操作！');
        // }
        // $username = get_model_value($this->request->post('id'), 'Member','username');
        if (DataService::update($this->table)) {
            LogService::write('系统用户', '系统用户禁用成功');
            // $hx_deactivate = $this->hx->hx_user_deactivate($username);
            // if($hx_deactivate){
                $this->success("用户禁用成功！", '');
            // }
        }
        $this->error("用户禁用失败，请稍候再试！");
    }

    /**
     * 用户禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        // $username = get_model_value($this->request->post('id'), 'Member','username');
        if (DataService::update($this->table)) {
            LogService::write('系统用户', '系统用户启用成功');
            // $hx_activate = $this->hx->hx_user_activate($username);
            // if($hx_activate){
                $this->success("用户启用成功！", '');
            // }
        }
        $this->error("用户启用失败，请稍候再试！");
    }

    /**
     * 取消认证
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbidAuth()
    {
        if (DataService::update($this->table)) {
            LogService::write('系统用户', '系统用户取消认证成功');
            $this->success("取消认证成功！", '');
        }
    }

    /**
     * 通过认证
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resumeAuth()
    {
        if (DataService::update($this->table)) {
            LogService::write('系统用户', '系统用户通过认证成功');
            $member = $this->member->getOneDarry(['id' => request()->post('id')]);
            send_wx_msg([
                    'title' => '用户认证成功通知', 
                    'description' => '恭喜您，用户认证成功！', 
                    'url' => get_root_url() . '/wap/member/auth', 
                    'picurl' => $member['avatar']
                ], $member['id']);
            $this->success("通过认证成功！", '');
        }
    }

    /**
     * 列表
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function use_log()
    {
        $this->title = '使用记录';
        list($get, $db) = [$this->request->get(), Db::name($this->tableLog)];
        foreach (['title','mid', 'uid', 'desc', 'status'] as $key) {
            if(isset($get[$key]) && $get[$key] !== ''){
                if($key == 'mid' || $key == 'uid' || $key == 'status'){
                    $db->where($key, $get[$key]);
                }else{
                    $db->whereLike($key, "%{$get[$key]}%");
                }
            }
        }
        if (isset($get['date']) && $get['date'] !== '') {
            list($start, $end) = explode(' - ', $get['date']);
            // $db->whereBetween('login_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
            $db->whereBetween('create_at', [strtotime("{$start} 00:00:00"), strtotime("{$end} 23:59:59")]);
        }
        return parent::_list($db->order('start_at desc'));
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _use_log_data_filter(&$data)
    {
        // halt($data);
        foreach ($data as &$vo) {
        }
    }

    /**
     * 列表
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function res_log()
    {
        $this->title = '预约记录';
        list($get, $db) = [$this->request->get(), Db::name($this->tableReserve)];
        foreach (['title','mid', 'uid', 'desc', 'status'] as $key) {
            if(isset($get[$key]) && $get[$key] !== ''){
                if($key == 'mid' || $key == 'uid' || $key == 'status'){
                    $db->where($key, $get[$key]);
                }else{
                    $db->whereLike($key, "%{$get[$key]}%");
                }
            }
        }
        if (isset($get['date']) && $get['date'] !== '') {
            list($start, $end) = explode(' - ', $get['date']);
            // $db->whereBetween('login_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
            $db->whereBetween('create_at', [strtotime("{$start} 00:00:00"), strtotime("{$end} 23:59:59")]);
        }
        return parent::_list($db->where(['is_deleted' => 0])->order('start_at desc'));
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _res_log_data_filter(&$data)
    {
        // halt($data);
        foreach ($data as &$vo) {
        }
    }

}
